//
//  ConfirmViewController.m
//  xingfugangwan
//
//  Created by rainday on 14/12/28.
//  Copyright (c) 2014年 rainday. All rights reserved.
//

#import "ConfirmViewController.h"
#import <ReactiveCocoa.h>
#import <RACEXTScope.h>
#import "SearchPreOrderViewController.h"
#import "BrandViewController.h"
#import "SiginingViewController.h"
#import <AFNetworking.h>

#import <MBProgressHUD.h>
#import "XFGWCart.h"
#import "SignSuccessViewController.h"
#import "NetIP.h"

#define LIST @[@[@"订单"],@[@"承办方"],@[@"备注",@"全款",@"预付款"],@[@"付款方式"],@[@"在线签名"]]

@interface ConfirmViewController ()<UITableViewDataSource,UITableViewDelegate,UIAlertViewDelegate,SearchPreOrderProtocol,BrandProtocol,UIActionSheetDelegate,SignProtocol,SignSuccessProtocol>

@property (nonatomic ,weak) IBOutlet UIButton *confirmButton;
@property (nonatomic ,strong) NSMutableDictionary *dic;

@property (nonatomic ,strong) NSString *brand;
@property (nonatomic ,strong) NSString *paystyle;
@property (nonatomic ,strong) NSString *extraSting;//备注
@property (nonatomic ,strong) NSString *allPay;    //全款
@property (nonatomic ,strong) NSString *prePay;    //预付款


@property (nonatomic ,weak) IBOutlet UITableView *tableView;
- (IBAction)confirmButton:(id)sender;

@end
static NSString *reuseIdentify = @"Cell";



@implementation ConfirmViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    _dic = [NSMutableDictionary dictionary];
    if ([_orderId length]>0) {
         [_dic setObject:_orderId forKey:@"订单号"];
    }
    
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentify];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuseIdentify];
        
        
        
    }
    
    
    cell.textLabel.text = LIST[indexPath.section][indexPath.row];
    
    if (indexPath.section==0 && _orderId) {
        
        cell.textLabel.text = [NSString stringWithFormat:@"%@%@",LIST[indexPath.section][indexPath.row],_orderId];
        
    }
    if (indexPath.section==1 && _brand) {
        cell.textLabel.text = [NSString stringWithFormat:@"%@:   %@",LIST[indexPath.section][indexPath.row],_brand];
        
    }
    
    if (indexPath.section==2) {
        switch (indexPath.row) {
            case 0:
                if (_extraSting) {
                    cell.textLabel.text = [NSString stringWithFormat:@"%@ :%@",LIST[indexPath.section][indexPath.row],_extraSting];
                }
                
                
                break;
            case 1:
                if (_allPay) {
                    cell.textLabel.text = [NSString stringWithFormat:@"%@ :%@",LIST[indexPath.section][indexPath.row],_allPay];
                }
                
                
                break;
            case 2:
                if (_prePay) {
                     cell.textLabel.text = [NSString stringWithFormat:@"%@ :%@",LIST[indexPath.section][indexPath.row],_prePay];
                }
               
                
                break;
            default:
                break;
        }
    }
    
    if (indexPath.section==3 && _paystyle) {
        cell.textLabel.text = [NSString stringWithFormat:@"%@:   %@",LIST[indexPath.section][indexPath.row],_paystyle];
        
    }
    
    if ([cell.textLabel.text isEqualToString:@"订单"] || [cell.textLabel.text isEqualToString:@"承办方"] || [cell.textLabel.text isEqualToString:@"付款方式"] ) {
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        
    }
    
    if ([cell.textLabel.text isEqualToString:@"在线签名"]) {
        
        NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/sign.png"];
        
        UIImage *image = [UIImage imageWithContentsOfFile:path];
        

        cell.imageView.image = image;
        
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    
    if (indexPath.section==2) {
        NSString *text = cell.textLabel.text;
        NSArray *textArray = [text componentsSeparatedByString:@":"];
        
        
        
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:[NSString stringWithFormat:@"请输入%@",textArray[0]] message:nil delegate:self cancelButtonTitle:@"好的" otherButtonTitles:nil, nil];
        alertView.alertViewStyle = UIAlertViewStylePlainTextInput;
        
        UITextField *tf = [alertView textFieldAtIndex:0];
        if (indexPath.row==0) {
            tf.keyboardType = UIKeyboardTypeDefault;
            
        }else{
            tf.keyboardType = UIKeyboardTypeNumberPad;
        }
        
        @weakify(cell)
        @weakify(self)
        [[tf rac_textSignal] subscribeNext:^(id x) {
            @strongify(cell)
            @strongify(self)
            cell.textLabel.text = [NSString stringWithFormat:@"%@ :%@",LIST[indexPath.section][indexPath.row],x];
            switch (indexPath.row) {
                case 0:
                    _extraSting = x;
                    
                    break;
                case 1:
                    if ([x isEqualToString:@""]) return ;
                    if (![self isPureInt:x]) {
                        [self performSelectorOnMainThread:@selector(showTipMessage:) withObject:@"请输入全款金额，阿拉伯数字足以表达" waitUntilDone:YES];
                        return ;
                    }
                    _allPay = x;
                    
                    break;
                case 2:
                    if (![self isPureInt:x]) {
                        
                    }
                    _prePay = x;
                    
                    break;
                default:
                    break;
            }
            id copyx = [x copy];
            [self.dic setObject:copyx forKey:LIST[indexPath.section][indexPath.row]];
            
            
        }];
        [alertView show];
    }
    
    
    if (indexPath.section ==0) {
        SearchPreOrderViewController *searchVC = [[SearchPreOrderViewController alloc] initWithNibName:@"SearchPreOrderViewController" bundle:nil];
        searchVC.delegate = self;
        [self presentViewController:searchVC animated:YES completion:nil];
    }
    
    if (indexPath.section==1) {
        BrandViewController *brandVC = [[BrandViewController alloc] initWithNibName:@"BrandViewController" bundle:nil];
        brandVC.delegate = self;
        [self presentViewController:brandVC animated:YES completion:nil];
    }
    
    if (indexPath.section ==3) {
        UIActionSheet *ation = [[UIActionSheet alloc] initWithTitle:@"选择支付方式" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"现金支付",@"POS支付", nil];
        [ation showInView:self.view];
        
    }
    
    if (indexPath.section==4) {
        SiginingViewController *signVC = [[SiginingViewController alloc] initWithNibName:@"SiginingViewController" bundle:nil];
        signVC.delegate = self;
        [self presentViewController:signVC animated:YES completion:nil];
        
    }
    
    
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return [LIST count];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 64;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 30;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [LIST[section] count];
}

- (void)hasSelectedOreder:(NSString *)serialNumber
{
    [_dic setObject:serialNumber forKey:@"订单号"];
    _orderId = serialNumber;
    [_tableView reloadData];

}

- (void)actionSheet:(UIActionSheet *)actionSheet didDismissWithButtonIndex:(NSInteger)buttonIndex
{
    switch (buttonIndex) {
        case 0:
            [_dic setObject:@"现金支付" forKey:@"支付方式"];
            _paystyle = @"现金支付";
            break;
        case 1:
            [_dic setObject:@"POS支付" forKey:@"支付方式"];
            _paystyle = @"POS支付";
            break;
        default:
            break;
    }
    [_tableView reloadData];
    [actionSheet removeFromSuperview];
    
}
- (void)hasSelectedBrand:(NSString *)name
{
    [_dic setObject:name forKey:@"品牌"];
    _brand = name;
    
    [_tableView reloadData];
}

- (void)saveSign:(UIImage *)image
{
    NSString *pngPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/sign.png"];
    
    
    // Write a UIImage to JPEG with minimum compression (best quality)
    // The value 'image' must be a UIImage object
    // The value '1.0' represents image compression quality as value from 0.0 to 1.0
    
     // Write image to PNG
    [UIImagePNGRepresentation(image) writeToFile:pngPath atomically:YES];
    
    
    // Let's check to see if files were successfully written...
    // Create file manager
    NSError *error;
    NSFileManager *fileMgr = [NSFileManager defaultManager];
    
    
    // Point to Document directory
    NSString *documentsDirectory = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
    
    NSLog(@"Documents directory: %@", [fileMgr contentsOfDirectoryAtPath:documentsDirectory error:&error]);
    [_tableView reloadData];
    
}
- (void)confirmButton:(id)sender
{
    
//    PayOnlineViewController *payVC = [[PayOnlineViewController alloc] initWithNibName:@"PayOnlineViewController" bundle:nil];
//    [self.navigationController pushViewController:payVC animated:nil];
//    return;
    
    XFGWCart *cart = [XFGWCart shareCart];
    NSDictionary *itemDic = cart.dictionary;
    NSArray *keysArray = itemDic.allKeys;
    if ([keysArray count]<1) {
        [self performSelectorOnMainThread:@selector(showTipMessage:) withObject:@"您还没有选择项目" waitUntilDone:YES];
        return;
    }
    
    NSMutableString *itemstring = [NSMutableString string];
    
    
    for (id item in itemDic) {
        
        NSString *string = [NSString stringWithFormat:@"%@共有%@个",item,[itemDic objectForKey:item]];
        if ([itemstring isEqualToString:@""]) {
            [itemstring appendString:string];
            continue;
            
        }
        [itemstring appendString:[NSString stringWithFormat:@".%@",string]];
        
        
    }
    
   
    
    [_dic setObject:itemstring forKey:@"项目"];
    
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    id  token = [userDefaults objectForKey:@"token"];
    
    
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    
    [manager.requestSerializer setValue:[NSString stringWithFormat:@"Token %@",token] forHTTPHeaderField:@"Authorization"];
    [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    [manager.requestSerializer setValue:@"application/json; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
    
    
    
    @weakify(self)
    
    [manager POST:[[NetIP shareNetAddress] getSigningURLString] parameters:_dic constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        
        NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/sign.png"];
        UIImage *image = [UIImage imageWithContentsOfFile:path];
        

        [formData appendPartWithFileData:UIImagePNGRepresentation(image)
                                    name:@"sign"
                                fileName:@"sign.png"
                                mimeType:@"image/png"];
        
        
        
        
        
    } success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        
       @strongify(self)
        if ([[responseObject objectForKey:@"state"] isEqualToString:@"success"]) {
            [self performSelectorOnMainThread:@selector(signSuccessWithDic:) withObject:responseObject waitUntilDone:YES];
        }else{
            [self performSelectorOnMainThread:@selector(showTipMessage:) withObject:[responseObject objectForKey:@"message"] waitUntilDone:YES];
        
        }
        
        
        NSLog(@"%@",responseObject);
        return ;
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"%@",error);
        
    }];

    
}

- (void)showTipMessage:(NSString *)message
{
    MBProgressHUD *hud = [[MBProgressHUD alloc] initWithView:self.view];
    [self.view addSubview:hud];
    hud.labelText = message;
    [hud showAnimated:YES whileExecutingBlock:^{
        sleep(1);
        
    }];
}



- (BOOL)isPureInt:(NSString*)string{
    NSScanner* scan = [NSScanner scannerWithString:string];
    int val;
    return[scan scanInt:&val] && [scan isAtEnd];
}


- (void)signSuccessWithDic:(NSDictionary *)dic
{
    NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/sign.png"];
    NSFileManager *fileMgr = [NSFileManager defaultManager];
    [fileMgr removeItemAtPath:path error:nil];
    
    
    
    XFGWCart *cart = [XFGWCart shareCart];
    [cart.dictionary removeAllObjects];
    
    
    
    SignSuccessViewController *signSucess = [[SignSuccessViewController alloc] initWithNibName:@"SignSuccessViewController" bundle:nil orderid:[dic objectForKey:@"orderid"] price:[dic objectForKey:@"price"] payStyle:_paystyle];
    signSucess.advanceString = _prePay;
    
    signSucess.delegate = self;
    [self presentViewController:signSucess animated:YES completion:nil];
    
    
    
    
}

- (void)SignSuccessViewController:(SignSuccessViewController *)signSuccessViewController didPayPrice:(NSString *)price{
    
    [signSuccessViewController dismissViewControllerAnimated:YES completion:nil];
    [self.navigationController popToRootViewControllerAnimated:NO];
    
    
}
@end

